#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/6/27
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0

# 运行时不生成__pycache__

from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

from conf import config as cf
import yaml

class BasePage:
    def __init__(self, driver_base: WebDriver=None, element:dict=None):
        if driver_base is None:
            option = webdriver.ChromeOptions()
            option.debugger_address = "localhost:9222"
            self.driver = webdriver.Chrome(options=option)
            self.driver.get("https://work.weixin.qq.com/wework_admin/frame")
        else:
            self.driver = driver_base

        if element is None:
            with open(f"{cf.BASE_DIR}/selenium_0627/data/element.yaml", "r", encoding="utf-8") as f:
                self.element = yaml.safe_load(f)
        else:
            self.element = element


    def by_maps(self, element):
        maps = {
            "ID"               : By.ID,
            "XPATH"            : By.XPATH,
            "NAME"             : By.NAME,
            "PARTIAL_LINK_TEXT": By.PARTIAL_LINK_TEXT,
            "CSS": By.CSS_SELECTOR
        }
        return (maps[element["by"].upper()], element["locate"])


    def find(self, by, locate, outtime=3):
        ele:WebElement = WebDriverWait(self.driver, outtime, 1).until(EC.presence_of_element_located((by, locate)))
        return ele

    def finds(self, by, locate, outtime=3):
        eles: WebElement = WebDriverWait(self.driver, outtime, 1).until(EC.presence_of_all_elements_located((by,
                                                                                                            locate)))
        return eles

    def find_click(self, by, locate, outtime=3):
        self.find(by, locate, outtime).click()

    def find_send(self, by, locate, message, outtime=3):
        self.find(by, locate, outtime).send_keys(message)
